package com.example.dps;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.downpayment.dps.R;





public class SettingsActivity extends PreferenceActivity {
	
	String tag = "SettingsActivity";
	
	AccountDBHelper accountDBHelper;
	DBHelper dbHelper;
	HistoryHelper historyHelper;
	WebHelper webHelper;
	
    final int CLEAR_ACCOUNT_DIALOG = 1;
    final int UNLINK_ACCOUNT_DIALOG = 2;
    final int UNLINK_ACCOUNT_DIALOG_NOTLINKED = 3;
    final int CHANGE_MODE_DIALOG = 4;
    
    int selectedAccountID = -1;
    
	@Override
	public void onConfigurationChanged(Configuration newConfig){
		super.onConfigurationChanged(newConfig);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
    
	@Override
    public void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);      
        
        setTheme(R.style.PrefsTheme);
        
        this.getListView().setBackgroundDrawable(Utility.returnAdjustedBackgroundDrawable(this));

        
        addPreferencesFromResource(R.xml.preferences);       
        
        
        accountDBHelper = new AccountDBHelper(this);
        dbHelper = new DBHelper(this);
        historyHelper = new HistoryHelper(this);
        webHelper = new WebHelper(this);
        
        this.setAccountEntries();
        

        ListPreference changeAccountInfoPref = (ListPreference) this.getPreferenceScreen().findPreference("changeAccountInfoPref");
        
        changeAccountInfoPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){

			@Override
			public boolean onPreferenceChange(Preference pref, Object newValue) {

				//get the id of teh account
				int id = SettingsActivity.this.accountDBHelper.getAccountID(newValue.toString());
				
				//if account does not exist, do nothing
				if(id < 0) return false;
				
				Intent intent = new Intent(SettingsActivity.this, EditAccountActivity.class);
				
				intent.putExtra("accountName", newValue.toString());
				intent.putExtra("editAccount", true);
				
				
				SettingsActivity.this.startActivity(intent);
				
				return false;
				
			}
        	
        });
        
        
        Preference clearAccountPref = (Preference) this.getPreferenceScreen().findPreference("clearAccountPref");
        
        
        clearAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference arg0) {

				
				SettingsActivity.this.showDialog(CLEAR_ACCOUNT_DIALOG);
				
				
				return false;
			}
        	
        });
        
        Preference unlinkAccountPref = (Preference) this.getPreferenceScreen().findPreference("unlinkAccountPref");

        unlinkAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference arg0) {

				if(SettingsActivity.this.dbHelper.getMode() == DBHelper.EXISTING_ACCOUNT_MODE)
					SettingsActivity.this.showDialog(UNLINK_ACCOUNT_DIALOG);
				else SettingsActivity.this.showDialog(UNLINK_ACCOUNT_DIALOG_NOTLINKED);
				
				
				return false;
			}
        	
        });
        
        
        Preference changeLinkedAccountPref = (Preference) this.getPreferenceScreen().findPreference("changeLinkedAccountPref");
        
        changeLinkedAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference arg0) {
				
				Intent intent = new Intent(SettingsActivity.this, LinkExistingAccountActivity.class);
				SettingsActivity.this.startActivity(intent);
				
				return true;
				
			}
        	
        });
        
        
        Preference changeModePref = (Preference) this.getPreferenceScreen().findPreference("changeModePref");
        
        changeModePref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference arg0) {
				
				SettingsActivity.this.showDialog(CHANGE_MODE_DIALOG);
				return true;
			}
        	
        	
        	
        });
        
   
    }
    
    
    
    public void setAccountEntries(){
    	
    	ListPreference changeAccountInfoPref = (ListPreference) this.getPreferenceScreen().findPreference("changeAccountInfoPref");
    	//ListPreference clearAccountPref = (ListPreference) this.getPreferenceScreen().findPreference("clearAccountPref");
    	ListPreference withdrawDownPaymentPref = (ListPreference) this.getPreferenceScreen().findPreference("withdrawDownPaymentPref");
    	

        
        Cursor accountsCursor = accountDBHelper.getAccountsAsCursorNoDPS();
        
        
        if(accountsCursor.getCount() > 0){
        	String[] accountEntries = new String[accountsCursor.getCount()];
            
            accountsCursor.moveToFirst();
            for(int i = 0; i < accountsCursor.getCount(); i++){
            	accountsCursor.moveToPosition(i);
            	accountEntries[i] = accountsCursor.getString(accountsCursor.getColumnIndex(accountDBHelper.COLUMN_ACCOUNT_NAME));
            	
            }
            changeAccountInfoPref.setEntries(accountEntries);
            changeAccountInfoPref.setEntryValues(accountEntries);
            

            
            withdrawDownPaymentPref.setEntries(accountEntries);
            withdrawDownPaymentPref.setEntryValues(accountEntries);
        }
        else{
        	/** no accounts in table **/
        	String[] accountEntries = { "No accounts have been setup." };
        	
            changeAccountInfoPref.setEntries(accountEntries);
            changeAccountInfoPref.setEntryValues(accountEntries);
            

            
            withdrawDownPaymentPref.setEntries(accountEntries);
            withdrawDownPaymentPref.setEntryValues(accountEntries);
        	
        }
        
        accountsCursor.close();
        this.accountDBHelper.close();
        
    }
    
    

    
	@Override
	public Dialog onCreateDialog(int id) {
		
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		switch(id){
		
		case CLEAR_ACCOUNT_DIALOG:
			
		    builder.setMessage("Are you sure you would like to delete all account information?")
		    		.setNegativeButton("No", null)
		    		.setPositiveButton("Yes", new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {

							SettingsActivity.this.accountDBHelper.deleteAccounts();
							SettingsActivity.this.dbHelper.deleteUser();
							SettingsActivity.this.historyHelper.clearHistory();
							
							
							//refresh activity
							SettingsActivity.this.finish();
							Intent intent = new Intent(SettingsActivity.this, SettingsActivity.class);
							SettingsActivity.this.startActivity(intent);
							
						}
		    			
		    		});
		    
		    return builder.create();
		case UNLINK_ACCOUNT_DIALOG:
			builder.setMessage("Are you sure you would like to unlink your account?")
    		.setNegativeButton("No", null)
    		.setPositiveButton("Yes", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {


					SettingsActivity.this.webHelper.unlinkYodleeAccount();
					
					//refresh activity
					SettingsActivity.this.finish();
					Intent intent = new Intent(SettingsActivity.this, SettingsActivity.class);
					SettingsActivity.this.startActivity(intent);
					
				}
    			
    		});
			return builder.create();
			
		case UNLINK_ACCOUNT_DIALOG_NOTLINKED:
			builder.setMessage("You have not linked an existing bank account.");
			builder.setNegativeButton("Continue", null);
			return builder.create();
		    
			
		case CHANGE_MODE_DIALOG:
			builder = new AlertDialog.Builder(this);
			builder.setCancelable(true)
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			               public void onClick(DialogInterface dialog, int id) {
			               }
			           })
					.setTitle("You can view your savings on this screen by either:")
					.setItems(R.array.mode_selection_array, new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int which) {
		               // The 'which' argument contains the index position
		               // of the selected item
		            	   if(which == 2){// manual mode is 3rd element in array
		            		   SettingsActivity.this.dbHelper.setMode(DBHelper.MANUAL_MODE);
		            	   }
		            	   else if(which == 1){// manual mode is 3rd element in array
		            		   Intent intent = new Intent(SettingsActivity.this, SetupAccountActivity.class);
		            		   SettingsActivity.this.startActivity(intent);
		            	   }
		            	   else if(which == 0){// manual mode is 3rd element in array
		            		   Intent intent = new Intent(SettingsActivity.this, LinkExistingAccountActivity.class);
		            		   SettingsActivity.this.startActivity(intent);
		            	   }
		           }
		    });
		    return builder.create();
			
		
		}
		

	    return builder.create();
	}
	

}
    
